package com.xy.biz.fd.manager.impl;

import com.google.gson.Gson;
import com.xy.biz.fd.domain.DocumentPermissions;
import com.xy.biz.fd.domain.bo.DocumentBO;
import com.xy.biz.fd.domain.bo.DocumentHistoryBO;
import com.xy.biz.fd.domain.bo.DocumentLogBO;
import com.xy.biz.fd.domain.enums.DocumentTypeEnum;
import com.xy.biz.fd.domain.resp.GetEditorInfoResponse;
import com.xy.biz.fd.manager.DocumentHistoryManager;
import com.xy.biz.fd.manager.DocumentLogManager;
import com.xy.biz.fd.manager.DocumentManager;
import com.xy.lang.domain.Result;
import com.xy.lang.exception.ObjectNotFoundException;
import com.xy.tool.context.UserContextHolder;
import com.xy.tool.gid.service.GidService;
import com.xy.tool.minio.domain.minio.entities.MinioFileInfo;
import com.xy.tool.minio.domain.minio.obj.ConvertBody;
import com.xy.tool.minio.domain.minio.obj.FileModel;
import com.xy.tool.minio.util.*;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author wwj
 * @Date 2021/1/22
 */
@Slf4j
@Component
public class MinioDocumentManager {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private FileUtility fileUtility;

    @Autowired
    private GidService gidService;

    @Autowired
    private DocumentManager documentManager;

    @Autowired
    private DocumentLogManager documentLogManager;

    @Autowired
    private DocumentHistoryManager documentHistoryManager;

    @Value("${files.docservice.secret}")
    private String secret;

    @Value("${files.docservice.url.api}")
    private String api;

    @Value("${filesize-max}")
    private String filesizeMax;

    @Value("${files.docservice.edited-docs}")
    private String editedDocs;

    @Value("${files.docservice.viewed-docs}")
    private String viewedDocs;

    @Value("${files.docservice.convert-docs}")
    private String convertDocs;

    @Value("${files.docservice.url.converter}")
    private String converterUrl;

    @Value("${files.docservice.img-types}")
    private String imgTypes;

    private static int convertTimeout = 120000;

    public MinioFileInfo[] GetStoredFiles(String userAddress) {
        String userHost = StringUtils.curUserHostAddress(userAddress);
        List<String> files;
        try {
            files = minioUtil.getFiles(MinioUtil.storageBucket, userHost);
        } catch (RuntimeException e) {
            return new MinioFileInfo[0];
        }
        ArrayList<MinioFileInfo> files2 = new ArrayList<>();
        files.forEach(file -> files2.add(new MinioFileInfo(file)));
        return files2.toArray(new MinioFileInfo[0]);
    }

    public String getInternalExtension(FileType fileType) {
        if (fileType.equals(FileType.Text))
            return ".docx";

        if (fileType.equals(FileType.Spreadsheet))
            return ".xlsx";

        if (fileType.equals(FileType.Presentation))
            return ".pptx";

        return ".docx";
    }

    public void createDemo(DocumentBO documentBO, String fileExt, Long uid, String uname) throws Exception {
        String demoName = "new" + fileExt;

        /**
         * 雪花算法生成对象名称
         */
        String minObjectName = getMinCorrectName(demoName);

        //InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(demoName);
        //改为MinIO加载模板
        InputStream inputStream = minioUtil.getObject(MinioUtil.templateBucket, demoName);

        Long size = minioUtil.uploadFile(inputStream, minObjectName, MinioUtil.storageBucket);

        createMinioMeta(minObjectName, uid.toString(), uname);
        documentBO.setFileSize(size);
        documentBO.setPath(minObjectName);
    }

    public void copyDocument(DocumentBO srcDocument, DocumentBO documentBO) {
        String minObjectName = getMinCorrectNameWithExt(srcDocument.getFileExtension());
        try {
            InputStream stream = minioUtil.getObject(MinioUtil.storageBucket, srcDocument.getPath());
            Long size = minioUtil.uploadFile(stream, minObjectName, MinioUtil.storageBucket);
            createMinioMeta(
                    minObjectName,
                    UserContextHolder.getUserId().toString(),
                    UserContextHolder.getUserName());
            documentBO.setFileSize(size);
            documentBO.setPath(minObjectName);
            documentBO.setThreadId(Long.valueOf(minObjectName.substring(0, minObjectName.indexOf("."))));
        } catch (Exception e) {
            log.error("文件复制失败！");
            throw new ObjectNotFoundException("文件复制失败！");
        }
    }

    public GetEditorInfoResponse generateInfoForEditor(String fileName, String minObjectName, Long userId, String userName, DocumentBO documentBO, String mode) throws Exception {
        FileModel file = new FileModel(
                fileName,
                minObjectName,
                userId + "",
                userName,
                documentBO.getActionLink(),
                minioUtil,
                fileUtility,
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(),
                editedDocs,
                mode,
                DocumentPermissions.hasDownload(documentBO.getPermission()),
                DocumentPermissions.hasPrint(documentBO.getPermission()));

        //新增访问记录
        DocumentBO doc = DocumentBO.builder().documentId(documentBO.getDocumentId()).accessTime(LocalDateTime.now()).build();
        int updateRows = documentManager.updateDocument(doc);
        DocumentLogBO documentLogBO = buildDocumentLog(documentBO);
        if (file.mode.equals("view")) {
            DocumentHistoryBO documentHistoryBO = DocumentHistoryBO.builder()
                    .documentHistoryId(null)
                    .documentId(documentBO.getDocumentId())
                    .documentName(documentBO.getDocumentName())
                    .accessType(0)
                    .accessTime(LocalDateTime.now())
                    .createUserId(UserContextHolder.getUserId())
                    .createTime(LocalDateTime.now())
                    .deleteFlag(false)
                    .build();
            int affectedRows = documentHistoryManager.saveDocumentHistory(documentHistoryBO);
            if (affectedRows > 0 && updateRows > 0) {
                documentLogBO.setAccessType(DocumentPermissions.PREVIEW);
                documentLogManager.saveDocumentLog(documentLogBO);
                Result.success();
            }
            Result.ofErrorRowsAffected();
        } else {
            DocumentHistoryBO documentHistoryBO = DocumentHistoryBO.builder()
                    .documentHistoryId(null)
                    .documentId(documentBO.getDocumentId())
                    .documentName(documentBO.getDocumentName())
                    .accessType(1)
                    .accessTime(LocalDateTime.now())
                    .createUserId(UserContextHolder.getUserId())
                    .createTime(LocalDateTime.now())
                    .deleteFlag(false)
                    .build();
            int affectedRows = documentHistoryManager.saveDocumentHistory(documentHistoryBO);
            if (affectedRows > 0 && updateRows > 0) {
                documentLogBO.setAccessType(DocumentPermissions.EDIT);
                documentLogManager.saveDocumentLog(documentLogBO);
                Result.success();
            }
            Result.ofErrorRowsAffected();
        }

        file.changeType(documentBO.getMode(),
                documentBO.getType(),
                editedDocs,
                DocumentPermissions.hasDownload(documentBO.getPermission()),
                DocumentPermissions.hasPrint(documentBO.getPermission()));
        String serialized = FileModel.Serialize(file);
        System.out.println(serialized);
        if (tokenEnabled()) {
            file.BuildToken();
        }
        return new GetEditorInfoResponse(serialized, api);
    }

    private boolean tokenEnabled() {
        return secret != null && !secret.isEmpty();
    }

    public void createMinioMeta(String minObjectName, String uid, String uname) throws Exception {
        String histDir = historyDir(minObjectName);
        JSONObject json = new JSONObject();

        json.put("created", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        json.put("id", (uid == null || uid.isEmpty()) ? "uid-1" : uid);
        json.put("name", (uname == null || uname.isEmpty()) ? "John Smith" : uname);

        String meta = histDir + "/" + "createdInfo.json";

        minioUtil.putObject(MinioUtil.storageBucket, meta, new ByteArrayInputStream(json.toJSONString().getBytes("UTF-8")));
    }

    public String historyDir(String storagePath) {
        return storagePath += "-hist";
    }


    public String getMinCorrectName(String fileName) {
        Long baseName = gidService.generate();
        String ext = fileUtility.getFileExtension(fileName);
        String minFileName = baseName + ext;
        return minFileName;
    }

    public String getMinCorrectNameWithExt(String ext) {
        Long baseName = gidService.generate();
        String minFileName = baseName + ext;
        return minFileName;
    }

    public String getCorrectName(String fileName) {
        String baseName = fileUtility.getFileNameWithoutExtension(fileName);
        String ext = fileUtility.getFileExtension(fileName);
        String name = baseName + ext;
        return name;
    }

    public String minioStoragePath(String fileName) {
        String directory = minioFilesRootPath();
        return directory + "/" + fileName;
    }

    private String minioFilesRootPath() {
        return curUserHostAddress(null);
    }

    private String curUserHostAddress(String userAddress) {
        if (userAddress == null) {
            try {
                userAddress = InetAddress.getLocalHost().getHostAddress();
            } catch (Exception ex) {
                userAddress = "";
            }
        }

        return userAddress.replaceAll("[^0-9a-zA-Z.=]", "_");
    }


    public int getMinioFileVersion(String histDir) {
        return minioUtil.fileVersion(MinioUtil.storageBucket, histDir);
    }

    public String VersionDir(String histDir, Integer nextVer) {
        return histDir + "/" + nextVer;
    }

    public Long passToMinioFile(String url, String minioStoragePath) {
        if (url == null || url.isEmpty()) {
            throw new RuntimeException("argument url");
        }
        if (minioStoragePath == null) {
            throw new RuntimeException("argument path");
        }
        URL uri = null;
        InputStream stream = null;
        java.net.HttpURLConnection connection = null;
        try {
            uri = new URL(url);
            connection = (java.net.HttpURLConnection) uri.openConnection();
            stream = connection.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        if (stream == null) {
            throw new RuntimeException("Stream is null");
        }

        Long size;
        try {
            size = minioUtil.uploadFile(stream, minioStoragePath, MinioUtil.storageBucket);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

        connection.disconnect();
        return size;
    }

    public long getMaxFileSize() {
        long size;

        try {
            size = Long.parseLong(filesizeMax);
        } catch (Exception ex) {
            size = 0;
        }

        return size > 0 ? size : 5 * 1024 * 1024;
    }

    public List<String> getFileExts() {
        List<String> res = new ArrayList<>();

        res.addAll(GetViewedExts());
        res.addAll(GetEditedExts());
        res.addAll(getConvertExts());
        res.addAll(getImgTypesExts());

        return res;
    }

    public List<String> GetViewedExts() {
        return Arrays.asList(viewedDocs.split("\\|"));
    }

    public List<String> GetEditedExts() {
        return Arrays.asList(editedDocs.split("\\|"));
    }

    public List<String> getConvertExts() {
        return Arrays.asList(convertDocs.split("\\|"));
    }

    public List<String> getImgTypesExts() {
        return Arrays.asList(imgTypes.split("\\|"));
    }
    public void removeObject(final String bucketName, final String fileName) throws Exception {
        minioUtil.removeObject(bucketName, fileName);
    }

    public DocumentBO upLoadDocument(MultipartHttpServletRequest request) {
        DocumentBO documentBO;
        try {
            MultipartFile file = request.getFile("file");
            Objects.requireNonNull(file);
            documentBO = upload(file);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return documentBO;
    }

    public List<DocumentBO> upLoadDocumentList(MultipartHttpServletRequest request) {
        List<DocumentBO> documentBOS = new ArrayList<>();
        List<MultipartFile> files;
        try {
            MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
            files = multiFileMap.get("file");
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        try {
            for (MultipartFile file : files) {
                documentBOS.add(upload(file));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return documentBOS;
    }

    private DocumentBO upload(MultipartFile file) throws Exception {
        DocumentBO documentBO = new DocumentBO();
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名
        String curExt = fileUtility.getFileExtension(fileName);
        if (!getFileExts().contains(curExt)) {
            log.error("File type is not supported");
            throw new RuntimeException("File type is not supported");
        }
        InputStream fileStream = file.getInputStream();
        FileType fileType = fileUtility.GetFileType(fileName);
        String internalFileExt;
        //如果文件为图片类型将不做任何修改
        if (fileType.equals(FileType.Pdf)) {
            internalFileExt = curExt;
        } else {
            internalFileExt = getInternalExtension(fileType);
        }

        if (!curExt.equals(internalFileExt)) {
            //需要转换格式
            if (getConvertExts().contains(curExt)) {
                //首先文件上传
                String tmpFileName = gidService.generate() + curExt;
                minioUtil.uploadFile(fileStream, tmpFileName, MinioUtil.tmpBucket);

                String objectURL = minioUtil.getObjectURL(MinioUtil.tmpBucket, tmpFileName, null);
                String key = ServiceConverter.GenerateRevisionId(tmpFileName + "/" + minioUtil.lastModified(MinioUtil.tmpBucket, tmpFileName) + "000");
                String newFileUri = getConvertedUri(objectURL, curExt, internalFileExt, key, true, fileName);
                if (newFileUri.isEmpty()) {
                    log.error("文档格式转换失败:" + fileName + "->" + fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt);
                    throw new RuntimeException("文档格式转换失败:" + fileName + "->" + fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt);
                }

                String correctName = fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt;

                URL url = new URL(newFileUri);
                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                InputStream stream = connection.getInputStream();

                if (stream == null) {
                    throw new Exception("Stream is null");
                }
                //将格式转换后的文件流上传至文件服务器正确桶中
                String minObjectName = getMinCorrectName(correctName);
                Long size = minioUtil.uploadFile(stream, minObjectName, MinioUtil.storageBucket);
                createMinioMeta(minObjectName, UserContextHolder.getUserId().toString(), UserContextHolder.getUserName());
                //删除临时文件
                minioUtil.removeObject(MinioUtil.tmpBucket, tmpFileName);

                documentBO.setDocumentName(fileUtility.getFileNameWithoutExtension(fileName));

                setDocumentType(documentBO, internalFileExt);

                documentBO.setPath(minObjectName);

                documentBO.setDocumentFlowLock(false);

                documentBO.setMinObjectName(minObjectName);

                documentBO.setFileSize(size);

            } else {
                throw new RuntimeException("系统无法转换此文件格式：" + curExt + "!");
            }
        } else {
            //直接上传至文件服务器正确桶中
            String minObjectName = getMinCorrectName(fileName);
            Long size = minioUtil.uploadFile(fileStream, minObjectName, MinioUtil.storageBucket);
            createMinioMeta(minObjectName, UserContextHolder.getUserId().toString(), UserContextHolder.getUserName());
            documentBO.setDocumentName(fileUtility.getFileNameWithoutExtension(fileName));
            setDocumentType(documentBO, fileName.substring(fileName.lastIndexOf(".")));
            documentBO.setPath(minObjectName);
            documentBO.setMinObjectName(minObjectName);
            documentBO.setFileSize(size);
        }
        return documentBO;
    }

    /*public DocumentBO upLoadDocument(MultipartHttpServletRequest request) {
        DocumentBO documentBO = new DocumentBO();
        try {
            String fileName = httpPostedFile.getSubmittedFileName();

//            long curSize = httpPostedFile.getSize();
//            if (getMaxFileSize() < curSize || curSize <= 0)
//            {
//                log.error("File size is incorrect");
//                throw new RuntimeException("File size is incorrect");
//            }

            String curExt = fileUtility.getFileExtension(fileName);
            if (!getFileExts().contains(curExt)) {
                log.error("File type is not supported");
                throw new RuntimeException("File type is not supported");
            }

            InputStream fileStream = httpPostedFile.getInputStream();

            FileType fileType = fileUtility.GetFileType(fileName);

            String internalFileExt = getInternalExtension(fileType);

            if (!curExt.equals(internalFileExt)) {
                //需要转换格式
                if (getConvertExts().contains(curExt)) {
                    //首先文件上传
                    String tmpFileName = gidService.generate() + curExt;
                    minioUtil.uploadFile(fileStream, tmpFileName, MinioUtil.tmpBucket);

                    String objectURL = minioUtil.getObjectURL(MinioUtil.tmpBucket, tmpFileName, null);
                    String key = ServiceConverter.GenerateRevisionId(tmpFileName + "/" + minioUtil.lastModified(MinioUtil.tmpBucket, tmpFileName) + "000");
                    String newFileUri = getConvertedUri(objectURL, curExt, internalFileExt, key, true, fileName);
                    if (newFileUri.isEmpty()) {
                        log.error("文档格式转换失败:" + fileName + "->" + fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt);
                        throw new RuntimeException("文档格式转换失败:" + fileName + "->" + fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt);
                    }

                    String correctName = fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt;

                    URL url = new URL(newFileUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();

                    if (stream == null) {
                        throw new Exception("Stream is null");
                    }
                    //将格式转换后的文件流上传至文件服务器正确桶中
                    String minObjectName = getMinCorrectName(correctName);
                    Long size = minioUtil.uploadFile(stream, minObjectName, MinioUtil.storageBucket);
                    createMinioMeta(minObjectName, UserContextHolder.getUserId().toString(), UserContextHolder.getUserName());
                    //删除临时文件
                    minioUtil.removeObject(MinioUtil.tmpBucket, tmpFileName);

                    documentBO.setDocumentName(fileUtility.getFileNameWithoutExtension(fileName));

                    setDocumentType(documentBO, internalFileExt);

                    documentBO.setPath(minObjectName);

                    documentBO.setMinObjectName(minObjectName);

                    documentBO.setFileSize(size);

                } else {
                    throw new RuntimeException("系统无法转换此文件格式：" + curExt + "!");
                }
            } else {
                //直接上传至文件服务器正确桶中
                String minObjectName = getMinCorrectName(fileName);
                Long size = minioUtil.uploadFile(fileStream, minObjectName, MinioUtil.storageBucket);
                createMinioMeta(minObjectName, UserContextHolder.getUserId().toString(), UserContextHolder.getUserName());
                documentBO.setDocumentName(fileUtility.getFileNameWithoutExtension(fileName));
                setDocumentType(documentBO, fileName.substring(fileName.lastIndexOf(".")));
                documentBO.setPath(minObjectName);
                documentBO.setMinObjectName(minObjectName);
                documentBO.setFileSize(size);
            }
            return documentBO;

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }*/

    private void setDocumentType(DocumentBO documentBO, String internalFileExt) {
        if (DocumentTypeEnum.DOCUMENT.getExt().equals(internalFileExt)) {
            documentBO.setDocumentType(DocumentTypeEnum.DOCUMENT.getCode());
        } else if (DocumentTypeEnum.EXECL.getExt().equals(internalFileExt)) {
            documentBO.setDocumentType(DocumentTypeEnum.EXECL.getCode());
        } else if (DocumentTypeEnum.PPT.getExt().equals(internalFileExt)) {
            documentBO.setDocumentType(DocumentTypeEnum.PPT.getCode());
        } else if (DocumentTypeEnum.PDF.getExt().equals(internalFileExt)) {
            documentBO.setDocumentType(DocumentTypeEnum.PDF.getCode());
        }
    }

    public String getConvertedUri(String documentUri,
                                  String fromExtension,
                                  String toExtension,
                                  String documentRevisionId,
                                  Boolean isAsync, String title) throws Exception {

        ConvertBody body = new ConvertBody();
        body.setUrl(documentUri);
        body.setOutputtype(toExtension.replace(".", ""));
        body.setFiletype(fromExtension.replace(".", ""));
        body.setTitle(title);
        body.setKey(documentRevisionId);
        //这里设成true不能convert成功,遂设成false
        if (isAsync)
            body.setAsync(false);

        //先不考虑token

        Gson gson = new Gson();
        String bodyString = gson.toJson(body);

        byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);

        URL url = new URL(converterUrl);
        java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setFixedLengthStreamingMode(bodyByte.length);
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(convertTimeout);
        //不考虑token

        connection.connect();
        try (OutputStream os = connection.getOutputStream()) {
            os.write(bodyByte);
        }

        InputStream stream = connection.getInputStream();

        if (stream == null)
            throw new Exception("Could not get an answer");

        String jsonString = convertStreamToString(stream);

        connection.disconnect();

        return getResponseUri(jsonString);
    }

    private String convertStreamToString(InputStream stream) throws IOException {
        InputStreamReader inputStreamReader = new InputStreamReader(stream);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = bufferedReader.readLine();

        while (line != null) {
            stringBuilder.append(line);
            line = bufferedReader.readLine();
        }

        String result = stringBuilder.toString();

        return result;
    }

    private String getResponseUri(String jsonString) throws Exception {
        JSONObject jsonObj = convertStringToJSON(jsonString);

        Object error = jsonObj.get("error");
        if (error != null)
            processConvertServiceResponceError(Math.toIntExact((long) error));

        Boolean isEndConvert = (Boolean) jsonObj.get("endConvert");

        Long resultPercent = 0l;
        String responseUri = null;

        if (isEndConvert) {
            resultPercent = 100l;
            responseUri = (String) jsonObj.get("fileUrl");
        } else {
            resultPercent = (Long) jsonObj.get("percent");
            resultPercent = resultPercent >= 100l ? 99l : resultPercent;
        }

        return resultPercent >= 100l ? responseUri : "";
    }

    private JSONObject convertStringToJSON(String jsonString) throws ParseException {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(jsonString);
        JSONObject jsonObj = (JSONObject) obj;

        return jsonObj;
    }

    private static void processConvertServiceResponceError(int errorCode) throws Exception {
        String errorMessage = "";
        String errorMessageTemplate = "Error occurred in the ConvertService: ";

        switch (errorCode) {
            case -8:
                errorMessage = errorMessageTemplate + "Error document VKey";
                break;
            case -7:
                errorMessage = errorMessageTemplate + "Error document request";
                break;
            case -6:
                errorMessage = errorMessageTemplate + "Error database";
                break;
            case -5:
                errorMessage = errorMessageTemplate + "Error unexpected guid";
                break;
            case -4:
                errorMessage = errorMessageTemplate + "Error download error";
                break;
            case -3:
                errorMessage = errorMessageTemplate + "Error convertation error";
                break;
            case -2:
                errorMessage = errorMessageTemplate + "Error convertation timeout";
                break;
            case -1:
                errorMessage = errorMessageTemplate + "Error convertation unknown";
                break;
            case 0:
                break;
            default:
                errorMessage = "ErrorCode = " + errorCode;
                break;
        }

        throw new Exception(errorMessage);
    }


    public String downloadFile(String path) {
        try {
            return minioUtil.getObjectURL(MinioUtil.storageBucket, path, null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取文件流
     * @param path
     * @return
     * @throws Exception
     */
    public InputStream getFileInputStream(String path) throws Exception {
        return minioUtil.getObject(MinioUtil.storageBucket, path);
    }

    private DocumentLogBO buildDocumentLog(DocumentBO documentBO) {
        DocumentLogBO documentLogBO = new DocumentLogBO();
        documentLogBO.setDocumentId(documentBO.getDocumentId());
        documentLogBO.setDocumentName(documentBO.getDocumentName());
        documentLogBO.setCreateTime(LocalDateTime.now());
        documentLogBO.setCreateUserId(UserContextHolder.getUserId());
        documentLogBO.setVersion(documentBO.getVersion());
        documentLogBO.setTenantId(UserContextHolder.getTenantId());
        documentLogBO.setDeleteFlag(false);
        return documentLogBO;
    }
}
